package com.ucode.admin.cgms.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.ucode.cgms.service.CgmsCompanionCategoryService;
import com.ucode.cgms.service.CgmsSpecialZoneService;
import com.ucode.model.cgms.CgmsCompanionCategory;
import com.ucode.model.cgms.CgmsSpecialZone;
import com.ucode.model.cgms.convert.CgmsCompanionCategoryConvert;
import com.ucode.model.cgms.form.CgmsCompanionCategoryForm;
import com.ucode.model.cgms.vo.CgmsCompanionCategoryVO;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.base.enums.CommonSwitchStatusEnum;
import com.ucode.tool.util.CollectionUtils;
import com.ucode.tool.util.IdentifyUtils;
import com.ucode.tool.validator.InEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Tag(name = "管理后台 - 陪玩社区系统 - 专区分类配置")
@RestController
@RequestMapping("/cgms/companion-category")
@Validated
public class CgmsCompanionCategoryController {

    @Resource
    private CgmsCompanionCategoryService cgmsCompanionCategoryService;
    @Resource
    private CgmsSpecialZoneService cgmsSpecialZoneService;

    @GetMapping("/page-list")
    @Operation(summary = "获得分页列表")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-category:query')")
    public ResponseResult<Paginator<CgmsCompanionCategoryVO>> pageList(
            @Schema(description = "分类名称") @RequestParam(value = "name",required = false) String name,
            @Schema(description = "专区编号") @RequestParam(value = "zoneId",required = false) Long zoneId,
            @Schema(description = "状态,参见CommonSwitchStatusEnum枚举类",allowableValues = {"0","1"}) @RequestParam(value = "status",required = false) Integer status,
            @Schema(description = "创建时间区间",example = "[2022-07-01 00:00:00,2022-07-01 23:59:59]")  @RequestParam(value = "createTimeInterval",required = false) LocalDateTime[] createTimeInterval,
            @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){

        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(name))
            condition.put("name", StrUtil.concat(true,"%", name,"%"));
        if(ArrayUtil.isNotEmpty(createTimeInterval) && createTimeInterval.length == 2){
            condition.put("startTime",createTimeInterval[0]);
            condition.put("endTime",createTimeInterval[1]);
        }
        condition.put("zoneId",zoneId);
        condition.put("status",status);
        condition.put("deltag",false);

        Paginator<CgmsCompanionCategory> paginator = cgmsCompanionCategoryService.queryPageForList(condition,pageSize,pageNum);
        Paginator<CgmsCompanionCategoryVO> paginatorVO = CgmsCompanionCategoryConvert.INSTANCE.convertPage(paginator);
        if(CollUtil.isNotEmpty(paginatorVO.getList())) {
            Set<Long> zoneIds = CollectionUtils.convertSet(paginatorVO.getList(), CgmsCompanionCategoryVO::getZoneId);
            Map<Long, CgmsSpecialZone> map = cgmsSpecialZoneService.getMap(zoneIds);
            for(CgmsCompanionCategoryVO vo : paginatorVO.getList()){
                CgmsSpecialZone zone = map.get(vo.getZoneId());
                if(ObjUtil.isNotNull(zone)) {
                    vo.setZoneName(zone.getName());
                }
            }
        }

        return ResponseResult.success(paginatorVO);
    }

    @GetMapping("/list-simple-page")
    @Operation(summary = "分页获取精简信息列表(没有权限校验，公共查询接口)", description = "主要用于前端的下拉选项")
    public ResponseResult<Paginator<CgmsCompanionCategory>> simplePageList(@Schema(description = "关键字")  @RequestParam(value = "keyword",required = false) String keyword,
                                                                           @Schema(description = "专区编号") @RequestParam(value = "zoneId",required = false) Long zoneId,
                                                                           @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                                           @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(keyword))
            condition.put("keyword", StrUtil.concat(true,"%", keyword,"%"));
        condition.put("zoneId",zoneId);
        condition.put("deltag",false);

        Paginator<CgmsCompanionCategory> paginator = cgmsCompanionCategoryService.queryPageForList(condition,pageSize,pageNum);
        return ResponseResult.success(paginator);
    }

    @GetMapping("/getById/{id}")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH,example = "1024")
    @Operation(summary = "主键获得信息")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-category:query')")
    public ResponseResult<CgmsCompanionCategoryVO> getById(@PathVariable(name="id",required=true) Long id){
        CgmsCompanionCategory bean = cgmsCompanionCategoryService.validate(id);
        CgmsCompanionCategoryVO vo = CgmsCompanionCategoryConvert.INSTANCE.convert(bean);
        if(ObjUtil.isNotNull(bean.getZoneId())){
            CgmsSpecialZone zone = cgmsSpecialZoneService.selectByPrimaryKey(bean.getZoneId());
            if(ObjUtil.isNotNull(zone)) {
                vo.setZoneName(zone.getName());
            }
        }
        return ResponseResult.success(vo);
    }

    @PostMapping("/create")
    @Operation(summary = "创建")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-category:create')")
    public ResponseResult<Long> create(@Valid @RequestBody CgmsCompanionCategoryForm form) {
        CgmsCompanionCategory bean = CgmsCompanionCategoryConvert.INSTANCE.convert(form);
        bean.setId(IdentifyUtils.getDefaultSnowflakeId());
        Long id = cgmsCompanionCategoryService.insert(bean);
        return id != null ? ResponseResult.success(id) : ResponseResult.failed();
    }

    @PostMapping("/update/{id}")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH,example = "1024")
    @Operation(summary = "修改")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-category:update')")
    public ResponseResult<Object> update(@PathVariable(name="id",required=true) Long id,
                                         @Valid @RequestBody CgmsCompanionCategoryForm form) {
        CgmsCompanionCategory bean = CgmsCompanionCategoryConvert.INSTANCE.convert(form);
        bean.setId(id);
        int i = cgmsCompanionCategoryService.update(bean);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

    @PostMapping("/update-status")
    @Operation(summary = "修改状态")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-category:update')")
    public ResponseResult<Boolean> updateStatus(@Schema(description = "编号集合",requiredMode = Schema.RequiredMode.REQUIRED)
                                                @NotEmpty(message = "编号集合为空")@Size(min = 1,max = 20,message = "编号集合数量为1-20条")
                                                @RequestParam(value = "ids",required = true) List<Long> ids,
                                                @Schema(description = "状态",requiredMode = Schema.RequiredMode.REQUIRED,allowableValues = {"0","1"})
                                                @InEnum(value = CommonSwitchStatusEnum.class, message = "修改的状态值必须是 {value}")
                                                @RequestParam(value = "status",required = true) Integer status) {
        int i = cgmsCompanionCategoryService.updateStatus(ids, status);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }


    @PostMapping("/logic-delete/{id}")
    @Operation(summary = "转移到回收站")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH, example = "1024")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-category:logic-delete')")
    public ResponseResult<Object> logicDelete(@PathVariable(name="id",required=true) Long id) {
        //逻辑删除
        int i = cgmsCompanionCategoryService.logicDeletePrimaryKey(id);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

    @PostMapping("/batch-logic-delete")
    @Operation(summary = "批量转移到回收站")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-category:logic-delete')")
    public ResponseResult<Boolean> batchLogicDeletePrimaryKey(@Schema(description = "编号集合",requiredMode = Schema.RequiredMode.REQUIRED)
                                                @NotEmpty(message = "编号集合为空")@Size(min = 1,max = 20,message = "编号集合数量为1-20条")
                                                @RequestParam(value = "ids",required = true) List<Long> ids) {
        int i = cgmsCompanionCategoryService.logicDeleteByPrimaryKeys(ids);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

}
